package cathe

import (
	"fmt"
	"shop_srv/shop"
	"strconv"
)

func CartAdd(userId, goodsId int, getMap map[string]interface{}) error {
	key := fmt.Sprintf("cart:%d:%d", userId, goodsId)
	return Rdb.HMSet(ctx, key, getMap).Err()
}

// 查询商品是否存在
func ExstixGoods(userId, goodsId int) bool {
	key := fmt.Sprintf("cart:%d:%d", userId, goodsId)
	return Rdb.Exists(ctx, key).Val() == 1
}

// 如果商品存在，自增商品数量
func UpdateGoodsNum(userId, goodsId, num int) error {
	key := fmt.Sprintf("cart:%d:%d", userId, goodsId)
	return Rdb.HIncrBy(ctx, key, "num", int64(num)).Err()
}

// 删除商品
func DeleterGoods(userId, goodsId int) error {
	key := fmt.Sprintf("cart:%d:%d", userId, goodsId)
	return Rdb.Del(ctx, key).Err()
}

// 购物车列表
func CartList(userId int) (cartList []*shop.CartList, err error) {
	key := fmt.Sprintf("cart:%d:*", userId)
	keys := Rdb.Keys(ctx, key).Val()

	for _, k := range keys {
		CartGoods := Rdb.HGetAll(ctx, k).Val()

		goodsId, _ := strconv.Atoi(CartGoods["goodsId"])
		price, _ := strconv.ParseFloat(CartGoods["price"], 64)
		num, _ := strconv.Atoi(CartGoods["num"])
		cartList = append(cartList, &shop.CartList{
			UserId:  int64(userId),
			GoodsId: int64(goodsId),
			Title:   CartGoods["title"],
			Image:   CartGoods["image"],
			Price:   float32(price),
			Num:     int64(num),
		})
	}
	return
}
